package com.ibeetl.admin.aod.service.excel.processor.data;

import com.ibeetl.admin.aod.entity.DieImportTask;
import com.ibeetl.admin.aod.service.DieImportTaskService;
import com.ibeetl.admin.aod.service.excel.match.MatchManagerImpl;
import com.ibeetl.admin.aod.service.excel.processor.AbstractImportProcessor;
import com.ibeetl.admin.aod.service.excel.task.ExcelFilterTask;
import com.ibeetl.admin.aod.web.query.FilterQuery;
import com.ibeetl.admin.core.entity.CoreUser;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;

@Component
public class AodIndustryDataExcelFilterProcessor extends AbstractDataProcessor {

    @Autowired
    protected MatchManagerImpl matchManager;

    @Autowired
    protected DieImportTaskService dieImportTaskService;

    public void process(MultipartFile file, FilterQuery filterQuery, CoreUser coreUser) throws Exception {

        if (null == file) {
            throw new Exception("未上传文件,请重新上传文件");
        }

        String saveFilePath = System.getProperty("user.dir") + "/excelSave/" + System.currentTimeMillis();
        FileUtils.forceMkdir(new File(saveFilePath));


        File originalFile = matchManager.convertMultipartFile2File(saveFilePath, file);

        String batchNo = saveNewTask(originalFile.getName(), saveFilePath, coreUser);

        // 这里开始可以丢到线程池中执行
        executorService.submit(new ExcelFilterTask(filterQuery, batchNo, originalFile, matchManager));

    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    private String saveNewTask(String fileName, String fileSavePath, CoreUser coreUser) {
        String batchNo = matchManager.getBatchNo();
        DieImportTask dieImportTask = new DieImportTask();
        dieImportTask.setBatchNo(batchNo);
        dieImportTask.setImportType(DieImportTask.ImportType.EXCEL_FILTER.getValue());
        dieImportTask.setFileName(fileName);
        dieImportTask.setFileSavePath(fileSavePath);
        dieImportTask.setProcessStatus(DieImportTask.ProcessStatus.TO_BE_PROCESSED.getValue());
        dieImportTask.setPhysicsFlag(DieImportTask.NORMAL);
        dieImportTask.setCreateUser(coreUser.getName());
        dieImportTask.setCreateTime(new Date());
        dieImportTaskService.save(dieImportTask);
        return batchNo;
    }

}
